import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Typography, Tag, Button, message, Empty, Spin, Modal } from 'antd';
import axios from 'axios';
import { ClockCircleOutlined, EnvironmentOutlined, TeamOutlined, TrophyOutlined } from '@ant-design/icons';

const { Title, Paragraph } = Typography;

// 定义活动接口 (与 joinActivityPage.tsx 中的 Activity 接口一致)
interface Activity {
  id: number;
  club_id: number;
  title: string;
  type: string | null;
  description: string | null;
  location: string | null;
  start_time: string;
  end_time: string;
  signup_deadline: string;
  max_participants: number | null;
  points: string;
  created_at: string;
}

const RegisteredActivityPage: React.FC = () => {
  const [activities, setActivities] = useState<Activity[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [missedActivities, setMissedActivities] = useState<number[]>([]); // 存储已错过的活动ID

  useEffect(() => {
    fetchRegisteredActivities();
  }, []);

  const fetchRegisteredActivities = async () => {
    try {
      setLoading(true);
      setError(null);

      const userInfo = localStorage.getItem('userInfo');
      if (!userInfo) {
        window.alert('请先登录获取报名活动信息');
        setLoading(false);
        return;
      }
      const studentId = JSON.parse(userInfo).id; // Assuming the student ID is stored as 'id'

      if (!studentId) {
        window.alert('无法获取学生信息，请重新登录');
        setLoading(false);
        return;
      }

      console.log(`Fetching registered activities for student ID: ${studentId}`);

      // 1. 调用后端接口获取学生已报名的活动ID列表
      const registeredResponse = await axios.get(`http://localhost:5000/api/studentRegistered/${studentId}`);

      console.log('Registered Activities Response:', registeredResponse.data);

      if (registeredResponse.data.success && registeredResponse.data.data && Array.isArray(registeredResponse.data.data.records)) {
        const registeredActivityIds = registeredResponse.data.data.records.map((record: any) => record.activity_id);

        if (registeredActivityIds.length === 0) {
          setActivities([]); // No registered activities
          setLoading(false);
          // message.info('您还没有报名任何活动'); // Optional: show a message
          return;
        }

        // 2. 根据活动ID列表调用接口获取每个活动的详细信息
        const activityDetailsPromises = registeredActivityIds.map(async (activityId: number) => {
          try {
            const detailResponse = await axios.get(`http://localhost:5000/api/activityDetail/${activityId}`);
            if (detailResponse.data.success) {
              return detailResponse.data.data; // Return activity details
            } else {
              console.error(`获取活动详情失败 (ID: ${activityId}):`, detailResponse.data.message);
              return null; // Indicate failure for this activity
            }
          } catch (error) {
            console.error(`获取活动详情失败 (ID: ${activityId}):`, error);
            return null; // Indicate failure for this activity
          }
        });

        const activityDetails = await Promise.all(activityDetailsPromises);

        // Filter out any null results from failed detail fetches
        const validActivities = activityDetails.filter(activity => activity !== null) as Activity[];

        setActivities(validActivities);

      } else {
        console.error('获取已报名活动ID失败或数据格式不正确:', registeredResponse.data);
        setError('获取已报名活动列表失败：数据格式不正确');
        window.alert('获取已报名活动列表失败：数据格式不正确');
      }
    } catch (error: any) {
      console.error('获取已报名活动列表失败:', error);
      setError(error.response?.data?.message || '获取已报名活动列表失败');
      window.alert(error.response?.data?.message || '获取已报名活动列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取错过的活动列表
  const fetchMissedActivities = async (studentId: number) => {
    try {
      const response = await axios.get(`http://localhost:5000/api/studentAllMissed/${studentId}`);
      if (response.data.success) {
        const missedIds = response.data.data.records.map((record: any) => record.activity_id);
        setMissedActivities(missedIds);
      }
    } catch (error) {
      console.error('获取错过活动列表失败:', error);
    }
  };

  const formatDateTime = (dateTimeStr: string) => {
    try {
      return new Date(dateTimeStr).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    } catch (error) {
      return '无效日期';
    }
  };

  const handleCancelRegistration = async (activity: Activity) => {
    console.log('handleCancelRegistration called for activity:', activity.id);
    try {
      // 先检查是否已过报名截止时间
      if (!isBeforeDeadline(activity.signup_deadline)) {
        // message.info('该活动的报名时间已截止，不可取消报名。请联系社团管理员。');
        window.alert('该活动的报名时间已截止，不可取消报名。请联系社团管理员。');
        console.log('Signup deadline passed, showing message.');
        return; // 截止时间已过，直接返回
      }

      // 报名时间未截止，继续之前的取消流程
      const userInfo = localStorage.getItem('userInfo');
      console.log('userInfo from localStorage:', userInfo);
      if (!userInfo) {
        // message.error('请先登录');
        window.alert('请先登录');
        console.log('No userInfo found, returning.');
        return;
      }
      const studentId = JSON.parse(userInfo).id;
      console.log('studentId:', studentId);

      if (!studentId) {
         // message.error('无法获取学生信息，请重新登录');
         window.alert('无法获取学生信息，请重新登录');
         console.log('studentId is invalid, returning.');
         return;
      }

      // 使用浏览器原生的 confirm 对话框
      const isConfirmed = window.confirm('确定要取消该活动的报名吗？');

      console.log('Confirmation dialog result:', isConfirmed);

      if (isConfirmed) { // 如果用户点击了"确定"
        console.log('Confirmed, proceeding with API call.');
        try {
          const response = await axios.delete(`http://localhost:5000/api/cancelJoin/${studentId}/${activity.id}`);
          if (response.data.success) {
            // message.success('取消报名成功');
            window.alert('取消报名成功');
            console.log('Cancellation successful, fetching updated list.');
            // 刷新活动列表
            fetchRegisteredActivities();
          } else {
            console.log('Cancellation failed:', response.data.message);
            // message.error(response.data.message || '取消报名失败');
            window.alert(response.data.message || '取消报名失败');
          }
        } catch (error: any) {
          console.error('Error during API call:', error);
          // message.error(error.response?.data?.message || '取消报名失败');
          window.alert(error.response?.data?.message || '取消报名失败');
        }
      } else {
        console.log('Cancellation cancelled by user.');
      }

    } catch (error) {
      console.error('Error in handleCancelRegistration:', error);
      // message.error('操作失败，请重试');
      window.alert('操作失败，请重试');
    }
  };

  const isBeforeDeadline = (deadline: string) => {
    return new Date(deadline) > new Date();
  };

  // 判断活动是否开始
  const isActivityStarted = (startTime: string) => {
    return new Date(startTime) <= new Date();
  };

  // 判断活动是否结束
  const isActivityEnded = (endTime: string) => {
    return new Date(endTime) < new Date();
  };

  // 处理签到逻辑
  const handleSignIn = async (activity: Activity) => {
    console.log('handleSignIn called for activity:', activity.id);
    const userInfo = localStorage.getItem('userInfo');
    if (!userInfo) {
      window.alert('请先登录');
      return;
    }
    const studentId = JSON.parse(userInfo).id;

    // 检查活动是否开始
    if (!isActivityStarted(activity.start_time)) {
      window.alert('活动还没开始，无法签到。');
      return;
    }

    // 检查活动是否结束
    if (isActivityEnded(activity.end_time)) {
      try {
        // 调用接口将状态更新为missed
        const response = await axios.put(`http://localhost:5000/api/studentActivity/missed/${studentId}/${activity.id}`);
        if (response.data.success) {
          window.alert('该活动已经结束，已标记为未参加。');
          // 更新错过活动列表
          await fetchMissedActivities(studentId);
          // 刷新活动列表
          fetchRegisteredActivities();
        }
      } catch (error) {
        console.error('更新活动状态失败:', error);
        window.alert('更新活动状态失败');
      }
      return;
    }

    // 活动已开始且未结束，使用 prompt 弹出输入框获取签到码
    const signInCodeInput = window.prompt('请输入签到码：');
    if (signInCodeInput === null || signInCodeInput.trim() === '') {
      return;
    }

    // 从 localStorage 获取该活动的签到码
    const savedCodes = localStorage.getItem('activitySignInCodes');
    let correctCode = null;
    if (savedCodes) {
      try {
        const codes = JSON.parse(savedCodes);
        correctCode = codes[activity.id];
      } catch (error) {
        console.error('Failed to parse sign-in codes from localStorage:', error);
      }
    }

    // 比对签到码
    if (!correctCode || signInCodeInput.trim() !== correctCode) {
      window.alert('签到码不正确，请重试。');
      return;
    }

    // 签到码正确，继续签到流程
    try {
      const response = await axios.put(`http://localhost:5000/api/studentActivity/attend/${studentId}/${activity.id}`, {
        points_awarded: activity.points
      });
      if (response.data.success) {
        window.alert('签到成功！');
        fetchRegisteredActivities();
      }
    } catch (error) {
      console.error('签到失败:', error);
      window.alert('签到失败，请重试');
    }
  };

  if (loading) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Spin size="large" />
        <p style={{ marginTop: '16px' }}>加载中...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Title level={2}>我的参与</Title>
        <Empty description={error} />
        <Button type="primary" onClick={fetchRegisteredActivities} style={{ marginTop: '16px' }}>
          重试
        </Button>
      </div>
    );
  }

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>我的参与</Title>
      <Row gutter={[16, 16]}>
        {activities.length === 0 ? (
          <Col span={24}>
            <Empty description="暂无已报名的活动" />
          </Col>
        ) : (
          activities.map((activity) => (
            <Col xs={24} sm={12} md={8} lg={6} key={activity.id}>
              <Card
                hoverable
                title={activity.title}
                extra={<Tag color="blue">{activity.type || '未分类'}</Tag>}
              >
                <Paragraph ellipsis={{ rows: 2 }}>{activity.description || '暂无描述'}</Paragraph>
                <div style={{ marginBottom: '12px' }}>
                  <ClockCircleOutlined /> 开始时间：{formatDateTime(activity.start_time)}
                </div>
                <div style={{ marginBottom: '12px' }}>
                  <ClockCircleOutlined /> 结束时间：{formatDateTime(activity.end_time)}
                </div>
                <div style={{ marginBottom: '12px' }}>
                  <ClockCircleOutlined /> 报名截止：{formatDateTime(activity.signup_deadline)}
                </div>
                <div style={{ marginBottom: '12px' }}>
                  <EnvironmentOutlined /> {activity.location || '地点待定'}
                </div>
                <div style={{ marginBottom: '12px' }}>
                  <TeamOutlined /> 人数：{activity.max_participants || '不限'}
                </div>
                <div style={{ marginBottom: '12px' }}>
                  <TrophyOutlined /> 可获得积分：{activity.points || '0.00'}
                </div>
                {/* 根据是否到活动开始时间显示签到按钮 */}
                {isActivityEnded(activity.end_time) ? (
                  <Button type="primary" disabled>
                    已错过
                  </Button>
                ) : isActivityStarted(activity.start_time) ? (
                  <Button
                    type="primary"
                    onClick={() => handleSignIn(activity)}
                    style={{ marginTop: '10px' }}
                  >
                    去签到
                  </Button>
                ) : (
                  <Button type="primary" disabled>
                    未开始
                  </Button>
                )}
                <Button 
                  type="primary" 
                  danger 
                  block 
                  onClick={() => handleCancelRegistration(activity)}
                  style={{
                    marginTop: isActivityStarted(activity.start_time) ? '10px' : '0', // 如果有签到按钮，增加上边距
                  }}
                >
                  取消报名
                </Button>
              </Card>
            </Col>
          ))
        )}
      </Row>
    </div>
  );
};

export default RegisteredActivityPage;
